import { Injectable } from "@angular/core";
import { Response, RequestOptions, Http, ConnectionBackend, RequestOptionsArgs, Headers } from "@angular/http";
import { Observable } from "rxjs";
import { LoadingController } from 'ionic-angular';
import { isNullOrUndefined } from "util";
import { PubSubService } from "./pubSubService";
import { UserData } from "../providers/user-data";


@Injectable()
export class HttpInterceptor extends Http {
    private _urlWhite = ['/oauth/token'];
    loadsign: any;
    _pubsub: PubSubService;
    _userData: UserData;
    private _storage: Storage = localStorage;

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, pubsub: PubSubService, private loadingCtrl: LoadingController, userData: UserData) {
        super(backend, defaultOptions);
        this._pubsub = pubsub;
        this._userData = userData;
        console.log(loadingCtrl);
    }

    private getAccessToken() {
        return this._storage.getItem("token");
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        console.log("get in:" + url);
        return this.intercept(super.get(url, this.genHeaders(options)), url);
    }

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
        console.log("post in:" + url + ',body:' + body);
        return this.intercept(super.post(url, body, this.genHeaders(options)), url);
    }

    genHeaders(options?: RequestOptionsArgs): RequestOptionsArgs {
        options = options || {};
        //添加授权
        options.headers = options.headers || new Headers();
        if (!isNullOrUndefined(this.getAccessToken())) {
            options.headers.set('Authorization', 'Bearer ' + this.getAccessToken());
        }
        //如果没有格式,则设定为application/json
        if (options.headers.get('Content-Type') == undefined) {
            options.headers.set('Content-Type', 'application/json');
        }
        return options;
    }

    intercept_back(observable: Observable<Response>): Observable<Response> {
        this._pubsub.beforeRequest.emit("beforeRequestEvent");
        observable.subscribe(null, (err) => {
            console.log('request err');
            this._pubsub.afterRequest.emit("afterRequestEvent");
            this.handleError(err.status);
        }, () => {
            console.log('request complete');
            this._pubsub.afterRequest.emit("afterRequestEvent");
        });
        return observable;
    }

    intercept(observable: Observable<Response>, url: string): Observable<Response> {
        //白名单验证
        if (this.iswhiteUrl(url)) {
            //是白名单
            //todo
        } else {
            //不是白名单
            let token = localStorage.getItem("token");
            if (token) {
                let checkTokenExpires = this._userData.checkTokenExpires();
                console.log('请求拦截器：token是否过期' + checkTokenExpires);
                if (checkTokenExpires) {
                    //todo  refreshtoken APi
                    // this._userData.saveToken('{"access_token": "914e50c2177cae2a60e1a66dc07dd321","refresh_token": "940798de7e738b8e4caf89dfe674bf11","token_type": "BEARER","expires_in": 36000}');
                    console.log('拦截器token过期：' + localStorage.getItem('token'));
                }
            }
        }
        this.startPresentLoadingDefault();
        let rt: any = Observable.create((observer: any) => {
            observable.subscribe(res => {
                observer.next(res);
                this.exitPresentLoadingDefault();
            }, (err) => {
                console.log("进入拦截器的错误请求了：" + JSON.stringify(err));
                this.handleError(err.status);
            }, () => {
                observer.complete();//注意添加这句，否则有可能一些第三方的包不能正常使用，如ng2-translate
            }
            );
        });
        this.exitPresentLoadingDefault();
        return rt;
    }

    handleError(status: any) {
        this.exitPresentLoadingDefault();
        if (status === 0) {
            this._pubsub.errorToast.emit("请求响应错误，请检查网络");
        } else if (status === 400) {//BadRequest
            this._pubsub.errorToast.emit("错误请求");
        } else if (status === 404) {
            this._pubsub.errorToast.emit("请求链接不存在，请联系管理员");
        } else if (status === 500) {
            console.log("内部服务器错误,请联系系统管理员.");
            this._pubsub.errorToast.emit("服务器出错，请稍后再试");
        } else if (status === 401) {//没登陆
            this._pubsub.errorToast.emit("未知错误，请检查网络");
        } else if (status === 403) {//没权限
            this._pubsub.errorToast.emit("没有权限");
        } else if (status === 504) {//网关超时
            this._pubsub.errorToast.emit("网关超时");
        } else {

        }
    }


    //显示网络请求,资源加载在
    startPresentLoadingDefault() {
        this.loadsign = this.loadingCtrl.create({
            content: '正在努力读取数据...'
        });
        this.loadsign.present();
    }

    exitPresentLoadingDefault() {
        this.loadsign.dismiss();
    }

    //是否白名单
    iswhiteUrl(url: string): boolean {
        for (let _url in this._urlWhite) {
            if (url.indexOf(_url)) {
                return true;
            }
        }
        return false;
    }

}